<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>logback加载指定配置文件 - 负责和大饼的博客</title><meta name="Description" content="想专注于学点手艺"><meta property="og:title" content="logback加载指定配置文件" />
<meta property="og:description" content="logback加载指定配置文件 问题描述 logback默认会加载类路径下的logback.xml等文件。当把项目打包成fat-jar时，默认读" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://amath0312.github.com/logback_config/" />
<meta property="article:published_time" content="2019-08-28T00:01:17+08:00" />
<meta property="article:modified_time" content="2019-08-28T00:01:17+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="logback加载指定配置文件"/>
<meta name="twitter:description" content="logback加载指定配置文件 问题描述 logback默认会加载类路径下的logback.xml等文件。当把项目打包成fat-jar时，默认读"/>
<meta name="application-name" content="负责和大饼的博客">
<meta name="apple-mobile-web-app-title" content="负责和大饼的博客"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://amath0312.github.com/logback_config/" /><link rel="prev" href="https://amath0312.github.com/install_docker/" /><link rel="next" href="https://amath0312.github.com/install_nexus/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "logback加载指定配置文件",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/amath0312.github.com\/logback_config\/"
        },"genre": "posts","keywords": "java, logback, log","wordcount":  1698 ,
        "url": "https:\/\/amath0312.github.com\/logback_config\/","datePublished": "2019-08-28T00:01:17+08:00","dateModified": "2019-08-28T00:01:17+08:00","publisher": {
            "@type": "Organization",
            "name": "Author"},"author": {
                "@type": "Person",
                "name": "Author"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="负责和大饼的博客">负责和大饼的博客</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> Blog </a><a class="menu-item" href="/categories/"> Categories </a><a class="menu-item" href="/tags/"> Tags </a><a class="menu-item" href="/about/"> About </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="Search titles or contents..." id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="Search">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="Clear">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="Switch Theme">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="负责和大饼的博客">负责和大饼的博客</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="Search titles or contents..." id="search-input-mobile">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="Search">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="Clear">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                        Cancel
                    </a>
                </div><a class="menu-item" href="/posts/" title="">Blog</a><a class="menu-item" href="/categories/" title="">Categories</a><a class="menu-item" href="/tags/" title="">Tags</a><a class="menu-item" href="/about/" title="">About</a><a href="javascript:void(0);" class="menu-item theme-switch" title="Switch Theme">
                <i class="fas fa-adjust fa-fw"></i>
            </a></div>
    </div>
</header>
<div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div>
<main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">logback加载指定配置文件</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>Author</a></span>&nbsp;<span class="post-category">included in <a href="/categories/java/"><i class="far fa-folder fa-fw"></i>java</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2019-08-08">2019-08-08</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;1698 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;4 minutes&nbsp;</div>
        </div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#问题描述">问题描述</a></li>
    <li><a href="#解决办法-1">解决办法-1</a></li>
    <li><a href="#解决办法-2">解决办法-2</a></li>
    <li><a href="#附录">附录</a>
      <ul>
        <li><a href="#logbackxml">logback.xml</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><h1 id="logback加载指定配置文件">logback加载指定配置文件</h1>
<h2 id="问题描述">问题描述</h2>
<p>logback默认会加载类路径下的<code>logback.xml</code>等文件。当把项目打包成fat-jar时，默认读取jar包中的<code>logback.xml</code>，很不方便修改。如果可以加载jar包外的配置文件，更方便修改日志参数。</p>
<h2 id="解决办法-1">解决办法-1</h2>
<p>在执行jar时，可以增加<code>logback.configurationFile</code>参数，指定配置文件的路径。如：</p>
<div class="highlight"><pre class="chroma"><code class="language-shell" data-lang="shell">java -Dlogback.configurationFile<span class="o">=</span>config/logback.xml  -jar woc-0.0.1-SNAPSHOT-jar-with-dependencies.jar
</code></pre></div><p>需要修改日志参数时，修改config/logback.xml并重启即可生效。</p>
<h2 id="解决办法-2">解决办法-2</h2>
<p>定义如下方法：</p>
<div class="highlight"><pre class="chroma"><code class="language-java" data-lang="java">  <span class="cm">/**
</span><span class="cm">   * 设置logback.xml配置文件并加载
</span><span class="cm">   *
</span><span class="cm">   * @param configPath 配置文件路径名
</span><span class="cm">   */</span>
  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">initLogback</span><span class="o">(</span><span class="n">String</span> <span class="n">configPath</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">File</span> <span class="n">file</span> <span class="o">=</span> <span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="n">configPath</span><span class="o">);</span>
    <span class="n">LoggerContext</span> <span class="n">loggerContext</span> <span class="o">=</span> <span class="o">(</span><span class="n">LoggerContext</span><span class="o">)</span> <span class="n">LoggerFactory</span><span class="o">.</span><span class="na">getILoggerFactory</span><span class="o">();</span>
    <span class="n">JoranConfigurator</span> <span class="n">joranConfigurator</span> <span class="o">=</span> <span class="k">new</span> <span class="n">JoranConfigurator</span><span class="o">();</span>
    <span class="n">joranConfigurator</span><span class="o">.</span><span class="na">setContext</span><span class="o">(</span><span class="n">loggerContext</span><span class="o">);</span>
    <span class="n">loggerContext</span><span class="o">.</span><span class="na">reset</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
      <span class="n">joranConfigurator</span><span class="o">.</span><span class="na">doConfigure</span><span class="o">(</span><span class="n">file</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span>
          <span class="n">String</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="s">&#34;Load logback config file error. Message: &#34;</span><span class="o">,</span> <span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">()));</span>
    <span class="o">}</span>
    <span class="n">StatusPrinter</span><span class="o">.</span><span class="na">printInCaseOfErrorsOrWarnings</span><span class="o">(</span><span class="n">loggerContext</span><span class="o">);</span>
  <span class="o">}</span>
</code></pre></div><p>在系统启动时调用此方法，初始化Logback参数，传入的参数<code>configPath</code>即日志配置文件。</p>
<p>此方法的缺点是将项目与Logback绑定，侵入性较强，不方便替换日志框架。</p>
<h2 id="附录">附录</h2>
<h3 id="logbackxml">logback.xml</h3>
<div class="highlight"><pre class="chroma"><code class="language-xml" data-lang="xml"><span class="cp">&lt;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&gt;</span>
<span class="c">&lt;!--
</span><span class="c">scan：当此属性设置为true时，配置文件如果发生改变，将会被重新加载，默认值为true。
</span><span class="c">scanPeriod：设置监测配置文件是否有修改的时间间隔，如果没有给出时间单位，默认单位是毫秒当scan为true时，此属性生效。默认的时间间隔为1分钟。
</span><span class="c">debug：当此属性设置为true时，将打印出logback内部日志信息，实时查看logback运行状态。默认值为false。
</span><span class="c">--&gt;</span>
<span class="nt">&lt;configuration</span> <span class="na">scan=</span><span class="s">&#34;false&#34;</span> <span class="na">scanPeriod=</span><span class="s">&#34;60 seconds&#34;</span> <span class="na">debug=</span><span class="s">&#34;false&#34;</span><span class="nt">&gt;</span>
  <span class="c">&lt;!-- 定义日志的根目录 --&gt;</span>
  <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;LOG_HOME&#34;</span> <span class="na">value=</span><span class="s">&#34;.&#34;</span><span class="nt">/&gt;</span>
  <span class="c">&lt;!-- 定义日志文件名称 --&gt;</span>
  <span class="nt">&lt;property</span> <span class="na">name=</span><span class="s">&#34;appName&#34;</span> <span class="na">value=</span><span class="s">&#34;woc&#34;</span><span class="nt">&gt;&lt;/property&gt;</span>
  <span class="c">&lt;!-- ch.qos.logback.core.ConsoleAppender 表示控制台输出 --&gt;</span>
  <span class="nt">&lt;appender</span> <span class="na">name=</span><span class="s">&#34;stdout&#34;</span> <span class="na">class=</span><span class="s">&#34;ch.qos.logback.core.ConsoleAppender&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;Encoding&gt;</span>UTF-8<span class="nt">&lt;/Encoding&gt;</span>
    <span class="c">&lt;!--
</span><span class="c">    日志输出格式：%d表示日期时间，%thread表示线程名，%-5level：级别从左显示5个字符宽度
</span><span class="c">    %logger{50} 表示logger名字最长50个字符，否则按照句点分割。 %msg：日志消息，%n是换行符
</span><span class="c">    --&gt;</span>
    <span class="nt">&lt;layout</span> <span class="na">class=</span><span class="s">&#34;ch.qos.logback.classic.PatternLayout&#34;</span><span class="nt">&gt;</span>
      <span class="nt">&lt;pattern&gt;</span>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n<span class="nt">&lt;/pattern&gt;</span>
    <span class="nt">&lt;/layout&gt;</span>
  <span class="nt">&lt;/appender&gt;</span>

  <span class="c">&lt;!-- 滚动记录文件，先将日志记录到指定文件，当符合某个条件时，将日志记录到其他文件 --&gt;</span>
  <span class="nt">&lt;appender</span> <span class="na">name=</span><span class="s">&#34;appLogAppender&#34;</span> <span class="na">class=</span><span class="s">&#34;ch.qos.logback.core.rolling.RollingFileAppender&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;Encoding&gt;</span>UTF-8<span class="nt">&lt;/Encoding&gt;</span>
    <span class="c">&lt;!-- 指定日志文件的名称 --&gt;</span>
    <span class="nt">&lt;file&gt;</span>${LOG_HOME}/${appName}.log<span class="nt">&lt;/file&gt;</span>
    <span class="c">&lt;!--
</span><span class="c">    当发生滚动时，决定 RollingFileAppender 的行为，涉及文件移动和重命名
</span><span class="c">    TimeBasedRollingPolicy： 最常用的滚动策略，它根据时间来制定滚动策略，既负责滚动也负责出发滚动。
</span><span class="c">    --&gt;</span>
    <span class="nt">&lt;rollingPolicy</span> <span class="na">class=</span><span class="s">&#34;ch.qos.logback.core.rolling.TimeBasedRollingPolicy&#34;</span><span class="nt">&gt;</span>
      <span class="c">&lt;!--
</span><span class="c">      滚动时产生的文件的存放位置及文件名称 %d{yyyy-MM-dd}：按天进行日志滚动
</span><span class="c">      %i：当文件大小超过maxFileSize时，按照i进行文件滚动
</span><span class="c">      --&gt;</span>
      <span class="nt">&lt;fileNamePattern&gt;</span>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.log<span class="nt">&lt;/fileNamePattern&gt;</span>
      <span class="c">&lt;!--
</span><span class="c">      可选节点，控制保留的归档文件的最大数量，超出数量就删除旧文件。假设设置每天滚动，
</span><span class="c">      且maxHistory是365，则只保存最近365天的文件，删除之前的旧文件。注意，删除旧文件是，
</span><span class="c">      那些为了归档而创建的目录也会被删除。
</span><span class="c">      --&gt;</span>
      <span class="nt">&lt;MaxHistory&gt;</span>365<span class="nt">&lt;/MaxHistory&gt;</span>
      <span class="c">&lt;!--
</span><span class="c">      当日志文件超过maxFileSize指定的大小是，根据上面提到的%i进行日志文件滚动 注意此处配置SizeBasedTriggeringPolicy是无法实现按文件大小进行滚动的，必须配置timeBasedFileNamingAndTriggeringPolicy
</span><span class="c">      --&gt;</span>
      <span class="nt">&lt;timeBasedFileNamingAndTriggeringPolicy</span> <span class="na">class=</span><span class="s">&#34;ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP&#34;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;maxFileSize&gt;</span>100MB<span class="nt">&lt;/maxFileSize&gt;</span>
      <span class="nt">&lt;/timeBasedFileNamingAndTriggeringPolicy&gt;</span>
    <span class="nt">&lt;/rollingPolicy&gt;</span>
    <span class="c">&lt;!--
</span><span class="c">    日志输出格式：%d表示日期时间，%thread表示线程名，%-5level：级别从左显示5个字符宽度 %logger{50} 表示logger名字最长50个字符，否则按照句点分割。 %msg：日志消息，%n是换行符
</span><span class="c">    --&gt;</span>
    <span class="nt">&lt;layout</span> <span class="na">class=</span><span class="s">&#34;ch.qos.logback.classic.PatternLayout&#34;</span><span class="nt">&gt;</span>
      <span class="nt">&lt;pattern&gt;</span>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n<span class="nt">&lt;/pattern&gt;</span>
    <span class="nt">&lt;/layout&gt;</span>
  <span class="nt">&lt;/appender&gt;</span>

  <span class="c">&lt;!--
</span><span class="c">  logger主要用于存放日志对象，也可以定义日志类型、级别
</span><span class="c">  name：表示匹配的logger类型前缀，也就是包的前半部分
</span><span class="c">  level：要记录的日志级别，包括 TRACE &lt; DEBUG &lt; INFO &lt; WARN &lt; ERROR
</span><span class="c">  additivity：作用在于children-logger是否使用 rootLogger配置的appender进行输出，false：表示只用当前logger的appender-ref，true：表示当前logger的appender-ref和rootLogger的appender-ref都有效
</span><span class="c">  --&gt;</span>

  <span class="nt">&lt;logger</span> <span class="na">name=</span><span class="s">&#34;beer.coder&#34;</span> <span class="na">level=</span><span class="s">&#34;debug&#34;</span> <span class="na">additivity=</span><span class="s">&#34;true&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;appender-ref</span> <span class="na">ref=</span><span class="s">&#34;stdout&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;appender-ref</span> <span class="na">ref=</span><span class="s">&#34;appLogAppender&#34;</span><span class="nt">/&gt;</span>
  <span class="nt">&lt;/logger&gt;</span>

  <span class="c">&lt;!--
</span><span class="c">  root与logger是父子关系，没有特别定义则默认为root，任何一个类只会和一个logger对应，
</span><span class="c">  要么是定义的logger，要么是root，判断的关键在于找到这个logger，然后判断这个logger的appender和level。
</span><span class="c">  --&gt;</span>
  <span class="nt">&lt;root</span> <span class="na">level=</span><span class="s">&#34;debug&#34;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;appender-ref</span> <span class="na">ref=</span><span class="s">&#34;stdout&#34;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;appender-ref</span> <span class="na">ref=</span><span class="s">&#34;appLogAppender&#34;</span><span class="nt">/&gt;</span>
  <span class="nt">&lt;/root&gt;</span>
<span class="nt">&lt;/configuration&gt;</span>
</code></pre></div></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2019-08-08</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/java/">java</a>,&nbsp;<a href="/tags/logback/">logback</a>,&nbsp;<a href="/tags/log/">log</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/install_docker/" class="prev" rel="prev" title="安装docker"><i class="fas fa-angle-left fa-fw"></i>安装docker</a>
            <a href="/install_nexus/" class="next" rel="next" title="安装maven私服">安装maven私服<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.75.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2019 - 2020</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank"></a></span>&nbsp;|&nbsp;<span class="license">本文采用<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/autocomplete/autocomplete.min.js"></script><script type="text/javascript" src="/lib/algoliasearch/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{},"search":{"algoliaAppID":"JJRDOPDPLW","algoliaIndex":"amath_blog","algoliaSearchKey":"e529bedc6a3af35b53e2597f1c7550c2","highlightTag":"em","maxResultLength":10,"noResultsFound":"No results found","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
